#include "CGESound.h"

CGESound::CGESound(void)
{
	Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 );
}

CGESound::~CGESound(void)
{
	for(map<string,Mix_Chunk*>::iterator it = m_MapEffects.begin();it != m_MapEffects.end();it++)
	{
		Mix_FreeChunk(it->second);
	}
	m_MapEffects.clear();

	Mix_FreeMusic(m_Music);

	Mix_CloseAudio();
}

void CGESound::LoadEffect(string filename,string name)
{
	Mix_Chunk *effect = Mix_LoadWAV(filename.c_str());
	m_MapEffects.insert(make_pair(name,effect));
}

//crane:maybe in the future,we need more than one music,like effects.
void CGESound::LoadMusic(string filename,string name)
{
	 m_Music = Mix_LoadMUS(filename.c_str());
}

//crane:You can use this function play or pause the music.
//only call Mix_PlayMusic(),if you just need play.
void CGESound::PlayMusic(string name)
{
	if(Mix_PlayingMusic() == 0)
	{
		Mix_PlayMusic( m_Music, -1 );
	}
	else
	{
		//If the music is paused
		if( Mix_PausedMusic() == 1 )
		{
			//Resume the music
			Mix_ResumeMusic();
		}
		//If the music is playing
		else
		{
			//Pause the music
			Mix_PauseMusic();
		}
	}
}

void CGESound::StopMusic()
{
	Mix_HaltMusic();
}


////If music is being played


void CGESound::PlayEffect(string name)
{
	map<string, Mix_Chunk*>::iterator it = m_MapEffects.find(name);
	if(it == m_MapEffects.end())
	{
		throw "no this effect";
	}
	Mix_PlayChannel( -1, it->second, 0 );
}
